package com.cwt_taxi_xa;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.data.SijiInfo;
import com.cwt_taxi_xa.protocol.CardUtil;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.VersionBiz;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ActivityCardInfo extends CWTBaseActivity{
	final String TAG = "ActivityCardInfo";
//	LinearLayout ly_cardinfo;
//	ListView lv_info;
//	ImageView iv_cardpc;
//	TextView tv_carname;
//	Button bt_daoru;
//	String[] ss_info;

	ImageView iv_zfb, iv_order, iv_pic;
	TextView tv_name, tv_qiye, tv_car, tv_tel, tv_siji;

	TextView tv_allview;
	Button bt_daoru;

	String[] ss_EF08;
	String[] ss_EF0B;
	String[] ss_ALL;
	String carpc_path, ewm1, ewm2;

	public static boolean cardok = true;

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1001){
				ewm2 = "/mnt/sdcard/ewmNet.png";
				Bitmap bm = ActivityCamera.getLoacalBitmap(ewm2);
				if(bm!=null) iv_order.setImageBitmap(CardUtil.getewm2(bm));
			}else if(msg.what==1002){
				TTsFunction.speakText("聚合二维码下载失败");
			}else if(msg.what==1003){
				TTsFunction.speakText("读卡结束");
				setResult(456);
				finish();
			}

			if(msg.what==1018){
				carpc_path = (String) msg.obj;
				AppLog.e(carpc_path);
				Bitmap bm = ActivityCamera.getLoacalBitmap(carpc_path);
				if(bm!=null) iv_pic.setImageBitmap(bm);
			}

			else if(msg.what==1019){
				ss_EF0B = (String[]) msg.obj;
				if(ss_EF0B.length > 6){
					AppLog.savelog("聚合物二维码问题3："+ss_EF0B[6]);
				}

				ss_ALL = new String[ss_EF08.length+ss_EF0B.length];
				System.arraycopy(ss_EF08, 0, ss_ALL, 0, ss_EF08.length);
				System.arraycopy(ss_EF0B, 0, ss_ALL, ss_EF08.length, ss_EF0B.length);

				tv_qiye.setText(ss_EF0B[0]);
				tv_car.setText(ss_EF0B[1]);

//				String carn = DeviceBiz.getCarNumber();
//				carn = carn.substring(carn.length()-4);
//				if(!carn.equals("AAAA")&&!carn.equals(ss_EF0B[1].substring(ss_EF0B[1].length()-4))){
//					TTsFunction.speakText("资格证车牌不符，无法驾驶本车");
//					cardok = false;
//				}
				if(ss_EF0B.length > 6){
					startDLPic(ss_EF0B[6]);
				}else{
					startDLPic("st4447900527116740.union.png");
				}
			}
			else if(msg.what==1020){


				ewm1 = (String) msg.obj;
				AppLog.e("读卡器测试：handler收到1020-"+ewm1);
				AppLog.e(carpc_path);
				Bitmap bm = ActivityCamera.getLoacalBitmap(ewm1);
				if(bm!=null) iv_zfb.setImageBitmap(bm);


				if(!cardok){
					cardok = true;
					TTsFunction.speakText("这张卡片无法签到");

				}else{
					saveCardInfo(ss_ALL);
				}



			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_aa_cardinfo);

		iv_zfb = (ImageView) findViewById(R.id.iv_evm_zfb);
		iv_order = (ImageView) findViewById(R.id.iv_evm_order);
		iv_pic = (ImageView) findViewById(R.id.iv_pic);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_qiye = (TextView) findViewById(R.id.tv_qiye);
		tv_car = (TextView) findViewById(R.id.tv_carnum);
		tv_tel = (TextView) findViewById(R.id.tv_tel);
		tv_siji = (TextView) findViewById(R.id.tv_sijinum);
		tv_allview = (TextView) findViewById(R.id.tv_allview);
		bt_daoru = (Button) findViewById(R.id.bt_daoru);
		tv_allview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		bt_daoru.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});


		//关闭读卡器
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						for (int i = 0; i < 20; i++) {
//							try {
//								Thread.sleep(500);
//								CardUtil.sendTsm905Data(0x0016, Tools.parseHexStr2Byte("00"));
//								break;
//							} catch (Exception e) {
//							}
//						}
//					}
//				}).start();


//		ly_cardinfo = (LinearLayout) findViewById(R.id.ly_cardinfo);
//		lv_info = (ListView) findViewById(R.id.listView1);
//		iv_cardpc = (ImageView) findViewById(R.id.imageView1);
//		tv_carname = (TextView) findViewById(R.id.textView2);
//		bt_daoru = (Button) findViewById(R.id.bt_daoru);
//
//
//
//
//		if(Constants.sijiinfo==null){
//			finish();
//		}else{
//			try {
//				Bitmap bm = ActivityCamera.getLoacalBitmap(Constants.sijiinfo.getPhoto());
//				if(bm!=null) iv_cardpc.setImageBitmap(bm);
//
//
//	            File f=new File(Constants.SDPath+Constants.sijiinfo.getSijicode()+"/Info2.txt");
//	            int length=(int)f.length();
//	            byte[] buff=new byte[length];
//	            FileInputStream fin=new FileInputStream(f);
//	            fin.read(buff);
//	            fin.close();
//	            String result=new String(buff);
//	            String[] ss = result.split(VersionBiz.fj);
//
//	            tv_carname.setText(ss[4]);
//
//	            for (int i = 0; i < ss.length; i++) {
//					ss[i] = ((i+1)+" : [")+CardUtil.infoKeys[i]+"] "+ss[i];
//				}
//				ArrayAdapter<String> ad = new ArrayAdapter<>(ActivityCardInfo.this, android.R.layout.simple_list_item_1, ss);
//				lv_info.setAdapter(ad);
//
//
//	        }catch (Exception e){
//	            e.printStackTrace();
//	            finish();
//	        }
//		}





	}


	protected void startDLPic(final String string) {
		AppLog.savelog("聚合物二维码问题4："+string);
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 5; i++) {
					try {
						FileOutputStream fos = new FileOutputStream(new File("/mnt/sdcard/ewmNet.png"));
						//http://weixintest.xacbank.com.cn:9999/static/qrcode/tmp/
						fos.write(CardUtil.readStream("http://weixintest.xacbank.com.cn:9999/static/qrcode/tmp/"+string));
						fos.flush();
						fos.close();
						handler.sendEmptyMessage(1001);
						AppLog.savelog("聚合物二维码问题5："+"http://weixintest.xacbank.com.cn:9999/static/qrcode/tmp/"+string);
						break;
					} catch (Exception e) {
						e.printStackTrace();
						if(i==4){
							handler.sendEmptyMessage(1002);
						}
						AppLog.savelog("聚合物二维码问题6：\n"+e.getLocalizedMessage()+"\n"+e.getMessage());
					}
				}
			}
		}).start();
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String[] ss1 = getIntent().getStringArrayExtra("ss_info1");
		if(ss1!=null){
			tv_allview.setEnabled(false);
			bt_daoru.setVisibility(View.VISIBLE);
			ss_EF08 = ss1;
			tv_siji.setText("从业资格证："+ss_EF08[3]);
			tv_name.setText(ss_EF08[4]);
			tv_tel.setText(ss_EF08[18]);

			if(!ss_EF08[8].equals("1")){
				TTsFunction.speakText("年度审核不合格");
				cardok = false;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			try {
				Date d_card = sdf.parse(ss_EF08[16]);
				if(d_card.getTime()<System.currentTimeMillis()){
					TTsFunction.speakText("从业资格证已过期");
					cardok = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}else{
			tv_allview.setEnabled(true);
			bt_daoru.setVisibility(View.GONE);
			if(Constants.sijiinfo==null){
				finish();
			}else{
				try {
					Bitmap bm = ActivityCamera.getLoacalBitmap(Constants.sijiinfo.getPhoto());
					if(bm!=null) iv_pic.setImageBitmap(bm);

					bm = ActivityCamera.getLoacalBitmap(Constants.sijiinfo.getQrCode1());
					if(bm!=null) iv_zfb.setImageBitmap(bm);

					bm = ActivityCamera.getLoacalBitmap(Constants.sijiinfo.getQrCode2());
					if(bm!=null) iv_order.setImageBitmap(bm);

					File f=new File(Constants.SDPath+Constants.sijiinfo.getSijicode()+"/Info2.txt");
					int length=(int)f.length();
					byte[] buff=new byte[length];
					FileInputStream fin=new FileInputStream(f);
					fin.read(buff);
					fin.close();
					String result=new String(buff);
					String[] ss = result.split(VersionBiz.fj);

					tv_qiye.setText(ss[20]);
					tv_car.setText(ss[21]);

					tv_siji.setText("从业资格证："+ss[3]);
					tv_name.setText(ss[4]);
					tv_tel.setText(ss[18]);



				}catch (Exception e){
					e.printStackTrace();
					finish();
				}
			}
		}

		/**
		 * 判断年度审核状态
		 * 判断有效期
		 * 判断车牌号
		 */

		//st4447900527116740_union.png
//		Bitmap bm = ActivityCamera.getLoacalBitmap("/mnt/sdcard/st4447900527116740_union.png");
//		if(bm!=null) iv_order.setImageBitmap(CardUtil.getewm2(bm));




	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub
		if (type == 10088){
			handler.sendMessageDelayed(handler.obtainMessage(1018, obj), 1000);
		}
		if (type == 10089){
			handler.sendMessageDelayed(handler.obtainMessage(1019, obj), 1000);
		}
		if (type == 10090){
			AppLog.e("读卡器测试：sendMsg收到10090");
			handler.sendMessageDelayed(handler.obtainMessage(1020, obj), 1000);
		}
	}










	/**
	 * 读卡结束后保存卡信息到本地
	 * @param ss
	 */
	public void saveCardInfo(String[] ss){
		//保存sp卡号
		final String number = ss_EF08[3];
		DataUtil.savelastCarNum(number);
		savesijibiaoshi();

		//保存照片
		final String path = Constants.SDPath+number+"/司机照片.jpg";
		final String path1 = Constants.SDPath+number+"/二维码1.jpg";
		final String path2 = Constants.SDPath+number+"/二维码2.jpg";
		new Thread(){
			public void run() {
				try {
					AppLog.e("-------------------------------------==1");
					File file = new File(Constants.SDPath+number);
					if(!file.exists()){
						file.mkdir();
						AppLog.e("-------------------------------------==3");
					}
					AppLog.e("-------------------------------------==4");

					FileOutputStream fileOutputStream = null;
					InputStream inputStream = null;
					int hasRead=0;

					try {
						inputStream = new FileInputStream(carpc_path);
						fileOutputStream=new FileOutputStream(new File(path));
						AppLog.e("-------------------------------------==5");
						while((hasRead=inputStream.read())!=-1){
							fileOutputStream.write(hasRead);
						}
						fileOutputStream.close();
						inputStream.close();
						AppLog.e("-------------------------------------==6");
					} catch (Exception e) {
						e.printStackTrace();
					}


					try {
						inputStream = new FileInputStream(ewm1);
						fileOutputStream=new FileOutputStream(new File(path1));
						AppLog.e("-------------------------------------==7");
						hasRead=0;
						while((hasRead=inputStream.read())!=-1){
							fileOutputStream.write(hasRead);
						}
						fileOutputStream.close();
						inputStream.close();
						AppLog.e("-------------------------------------==8");
					} catch (Exception e) {
						e.printStackTrace();
					}


					try {
						inputStream = new FileInputStream(ewm2);
						fileOutputStream=new FileOutputStream(new File(path2));
						AppLog.e("-------------------------------------==9");
						hasRead=0;
						while((hasRead=inputStream.read())!=-1){
							fileOutputStream.write(hasRead);
						}
						fileOutputStream.close();
						inputStream.close();
						AppLog.e("-------------------------------------==10");
					} catch (Exception e) {
						e.printStackTrace();
					}


					ActivityWaitQD.daoru = true;
					handler.sendEmptyMessage(1003);
				} catch (Exception e) {
					e.printStackTrace();
				}

			};
		}.start();

		//保存司机文本信息到本地
		Constants.sijiinfo = new SijiInfo();
		//IC从业资格用户
		Constants.sijiinfo.setSigninTpye(1);
		//姓名
		Constants.sijiinfo.setName(ss_EF08[4]);

		//司机号
		Constants.sijiinfo.setSijicode(ss_EF08[3]);

		//企业号
//		Constants.sijiinfo.setQiyecode(ss_info2[12]);
		Constants.sijiinfo.setQiyecode("12345");

		//资格证有效期
		Constants.sijiinfo.setCertificateData(ss_EF08[16]);

		//照片
		Constants.sijiinfo.setPhoto(path);

		//星级1-5
		try {
			Constants.sijiinfo.setStar(Integer.parseInt(ss_EF08[19])+2);
		} catch (Exception e) {
			Constants.sijiinfo.setStar(5);
		}

		//所属公司
		Constants.sijiinfo.setCompanyname(ss_EF0B[0]);

		//监督电话
		Constants.sijiinfo.setMobile(ss_EF08[18]);

		//二维码
		Constants.sijiinfo.setQrCode1(path1);

		//二维码
		Constants.sijiinfo.setQrCode2(path2);

		//卡号
		//Constants.sijiinfo.setCardnum("000000");
		//Constants.sijiinfo.setCardnum(ss_EF0B[1]);

		Constants.sijiNow = true;

		//签到新加(十九项) 2019-06-04-------------------------------------
		if(ss_EF08 != null && ss_EF08.length > 15){
			try {
				Constants.sijiinfo.setTermNumber(Integer.parseInt(ss_EF08[0]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				Constants.sijiinfo.setStudentID(Integer.parseInt(ss_EF08[1]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			Constants.sijiinfo.setIdentityNumber(ss_EF08[2]);
			Constants.sijiinfo.setAddress(ss_EF08[5]);

			try {
				Constants.sijiinfo.setAge(Integer.parseInt(ss_EF08[6]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


			try {
				//政治面貌
				Constants.sijiinfo.setPoliticalStatus(Integer.parseInt(ss_EF08[7]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				//年度审核
				Constants.sijiinfo.setAnnualAudit(Integer.parseInt(ss_EF08[8]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				//从业资格证类别
				Constants.sijiinfo.setCertificateType(Integer.parseInt(ss_EF08[9]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//驾照号
			Constants.sijiinfo.setDriverLicense(ss_EF08[10]);

			try {
				//驾驶员性质
				Constants.sijiinfo.setDriverType(Integer.parseInt(ss_EF08[11]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//驾照档案编号
			Constants.sijiinfo.setDriverLicenseNumber(ss_EF08[12]);
			//驾照签发日期
			Constants.sijiinfo.setDriverLicenseCD(ss_EF08[13]);
			//驾照档案编号

			//资格证初次发证日期
			Constants.sijiinfo.setCertificateCD(ss_EF08[14]);
			//发证日期
			Constants.sijiinfo.setCardCD(ss_EF08[15]);
			try {
				//从业资格证状态
				Constants.sijiinfo.setCertificateState(Integer.parseInt(ss_EF08[17]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


		if(ss_EF0B != null && ss_EF0B.length > 6){
			//所属公司
			Constants.sijiinfo.setCompanyname(ss_EF0B[0]);
			//车牌号
			Constants.sijiinfo.setCardnum(ss_EF0B[1]);

			try {
				Constants.sijiinfo.setSupervCardState(Integer.parseInt(ss_EF0B[2]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Constants.sijiinfo.setSupervCardState(0);
			}

			try {
				Constants.sijiinfo.setSupervCardType(Integer.parseInt(ss_EF0B[3]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Constants.sijiinfo.setSupervCardType(0);
			}

			Constants.sijiinfo.setSupervCardSDate(ss_EF0B[4]);
			Constants.sijiinfo.setSupervCardDDate(ss_EF0B[5]);
		}

		//AppLog.i(TAG,"saveCardInfo info:" + Constants.sijiinfo);
		//保存信息文本
		VersionBiz.saveSijiInfo(number, Constants.sijiinfo, ss);
	}


	private void savesijibiaoshi() {
		for (int i = 0; i < 3; i++) {
			String sjcode = SPUtils.getParamString("sijilocdata"+i, "");
			if(sjcode.length()<1){
				SPUtils.setParam("sijilocdata"+i, DataUtil.getlastCarNum());
				return;
			}
			if(sjcode.equals(DataUtil.getlastCarNum())) return;
		}
		String[] codes = new String[3];
		codes[0] = DataUtil.getlastCarNum();
		codes[1] = SPUtils.getParamString("sijilocdata0", "");
		codes[2] = SPUtils.getParamString("sijilocdata1", "");
		for (int i = 0; i < codes.length; i++) {
			SPUtils.setParam("sijilocdata"+i, codes[i]);
		}
	}









}
